<!--
 * @Description: 团伙关系图形
 -->

<template>
  <!-- 为 ECharts 准备一个具备大小（宽高）的 DOM -->
  <!--<div class="guanxitu_box">
    <div v-show="!isNoneData" id="chart" style="width:100%;height:420px;"></div>
    <div v-show="isNoneData" class="none_box">暂无数据</div>
  </div> -->
  <div id="chart" style="width:100%;height:500px;"></div>
</template>
<script>
import * as alarmServiceApi from '@/api/sjsk/alarmService'
export default {
  props: ['data', 'leftList', 'type', 'lowNumEchart', 'middleNumEchart'],
  data() {
    return {
      /* nodes,
      links,
      List */
      newImg: [],
      imgArr: [
        'https://ps.ssl.qhimg.com/t013eebcd6d2135b0f6.jpg',
        'https://ps.ssl.qhimg.com/t013eebcd6d2135b0f6.jpg',
        'https://ps.ssl.qhimg.com/t013eebcd6d2135b0f6.jpg',
        'https://ps.ssl.qhimg.com/t013eebcd6d2135b0f6.jpg',
        'https://ps.ssl.qhimg.com/t018a19d596e53bf01a.jpg',
        'https://ps.ssl.qhimg.com/t013eebcd6d2135b0f6.jpg',
        'https://ps.ssl.qhimg.com/t013eebcd6d2135b0f6.jpg',
        'https://ps.ssl.qhimg.com/t011ed73d6a1a314d93.jpg',
        'https://ps.ssl.qhimg.com/t018a19d596e53bf01a.jpg',
        'https://ps.ssl.qhimg.com/t0116e4685c6e2f0675.jpg',
        'https://ps.ssl.qhimg.com/t011ed73d6a1a314d93.jpg'
      ],
      nodes: [
        {
          // 数据结构
          name: null,
          itemStyle: {
            normal: {
              color: ''
            }
          }
        }
      ],
      // 创建links
      links: [
        { source: '', target: '' } // 数据结构
      ],
      categoryArray: [{ name: '核心人' }, { name: '家人' }, { name: '朋友' }],
      jsondata: { categories: '', nodes: '', links: '' },
      lowNum: 0,
      middleNum: 0,
      List: [],
      isLoading: false,
      isNoneData: false
    }
  },
  watch: {
    leftList(value) {
      this.getChartList(this.data)
    },
    data(value) {
      if (this.leftList.length !== 0) {
        this.getChartList(value)
      }
    },
    middleNumEchart(value) {
      this.middleNum = value
      if (this.leftList.length !== 0) {
        this.getChart()
      }
    },
    lowNumEchart(value) {
      this.lowNum = value
      if (this.leftList.length !== 0) {
        this.getChart()
      }
    }
  },
  created() {},
  mounted() {
    this.middleNum = 0
    this.lowNum = 0
  },
  methods: {
    getChartList(data) {
      console.log(this.type)
      // 获取图数据
      this.isLoading = true
      this.isNoneData = false
      let api = null
      if(this.type==1) {
        api = alarmServiceApi.getGangRelationsInsideAnalysis(data)
      } else if(this.type==2) {
        api = alarmServiceApi.getGangRelationsExternal(data)
      }
      if(!api) return
      api.then(res => {
      // eventModelApi.getChartList(data).then(res => {
        this.List = []

        if (res.success) {
          if (res.result.length === 0) {
            this.isNoneData = true
          }
          this.List = res.result

          this.nodes = []
          this.links = []
          let oldArr = []
          let oldPhoneArr = []
          for (let i = 0; i < this.List.length; i++) {
            // 分两个循环，因为返回数据为[{name: null, innerMsisdn: "8613976834620", relateMsisdn: "8613337589889", amount: 1, type: 1, totalAmount: 1}...],要分别得到innerMsisdn和relateMsisdn
            let objAll = {}
            objAll.phone = ''
            objAll.type = ''
            objAll.value = ''
            objAll.totalAmount = ''
            objAll.codeName = this.List[i].name
            objAll.phone = this.List[i].innerMsisdn
            objAll.type = this.List[i].type
            objAll.value = this.List[i].totalAmount
            objAll.totalAmount = this.List[i].totalAmount
            objAll.bgangRelationsTaskNumbersList = this.List[0].bgangRelationsTaskNumbersList
            oldPhoneArr.push(objAll)
          }
          for (let i = 0; i < this.List.length; i++) {
            let objAll = {}
            objAll.phone = ''
            objAll.type = ''
            objAll.value = ''
            objAll.totalAmount = ''
            objAll.codeName = this.List[i].name
            objAll.phone = this.List[i].relateMsisdn
            objAll.type = this.List[i].type
            objAll.value = this.List[i].totalAmount
            objAll.totalAmount = this.List[i].totalAmount
            objAll.bgangRelationsTaskNumbersList = this.List[0].bgangRelationsTaskNumbersList
            oldPhoneArr.push(objAll)
            // 处理this.links需要的数据
            let link = {}
            link.source = ''
            link.target = ''
            this.links.push(link)
            this.links[i].source = this.List[i].innerMsisdn
            this.links[i].target = this.List[i].relateMsisdn
          }
          for (let i = 0; i < oldPhoneArr.length; i++) {
            // 1.先将主叫通联号码全部放到newArr中
            let obj = {}
            obj.name = ''
            obj.type = 0
            obj.totalAmount = 0
            obj.itemStyle = {
              normal: {
                color: '#EC808D',
                borderWidth: 1
              }
            }
            oldArr.push(obj)
            oldArr[i].codeName = oldPhoneArr[i].codeName
            oldArr[i].name = oldPhoneArr[i].phone
            oldArr[i].type = oldPhoneArr[i].type
            oldArr[i].value = oldPhoneArr[i].totalAmount
            oldArr[i].totalAmount = oldPhoneArr[i].totalAmount
            oldArr[i].bgangRelationsTaskNumbersList = oldPhoneArr[0].bgangRelationsTaskNumbersList
          }
          // 2.oldArr去重
          let newArr = []
          let obj = {}
          for (let i = 0; i < oldArr.length; i++) {
            if (!obj[oldArr[i].name]) {
              newArr.push(oldArr[i])
              obj[oldArr[i].name] = true
            }
          }
          for (let i = 0; i < newArr.length; i++) {
            let node = {}
            node.name = null
            node.itemStyle = {
              normal: {
                color: '#EC808D',
                borderWidth: 1
              }
            }
            node.totalAmount = 0
            node.type = 0
            this.nodes.push(node)
            this.nodes[i].codeName = newArr[i].codeName
            this.nodes[i].name = newArr[i].name
            this.nodes[i].totalAmount = newArr[i].totalAmount
            this.nodes[i].type = newArr[i].type
            this.nodes[i].value = newArr[i].totalAmount
            this.nodes[i].bgangRelationsTaskNumbersList = newArr[0].bgangRelationsTaskNumbersList
          }
          this.getChart()
        }
        this.isLoading = false
      })
    },
    highLight() {
      this.EC.dispatchAction({
        type: 'highlight',
        // 使用 seriesId 或 seriesIndex 或 seriesName 来定位 series.
        seriesIndex: 0,
        // 使用 dataIndex 来定位节点。
        dataIndex: '13564854758'
      })
    },
    getChart() {
      let that = this
      if (that.type === 1) {
        for (let i = 0; i < that.nodes.length; i++) {
          if (that.nodes[i].totalAmount >= 0 && that.nodes[i].totalAmount <= that.lowNum) {
            // 通联次数大于等于0且小于等于this.lowNum阈值为低
            that.nodes[i].itemStyle.normal.color = '#92939d'//'#EC808D'
          } else if (that.nodes[i].totalAmount >= that.lowNum && that.nodes[i].totalAmount <= that.middleNum) {
            // 通联次数大于等于this.lowNum且小于等于this.middleNum阈值为中
            that.nodes[i].itemStyle.normal.color = '#6766b8'//'#FACD91'
          } else if (that.nodes[i].totalAmount >= that.middleNum) {
            // 通联次数大于等于this.middleNum阈值为高
            that.nodes[i].itemStyle.normal.color = '#50a4ab'//'#81D3F8'
          }
        }
      }
      if (that.type === 2) {
        for (let i = 0; i < that.nodes.length; i++) {
          that.nodes[i].itemStyle.normal.color = '#6766b8'//'#EC808D' // 外部
          for (let f = 0; f < that.leftList.length; f++) {
            if (that.nodes[i].name === that.leftList[f].msisdn) {
              that.nodes[i].itemStyle.normal.color = '#92939d'//'#ff6600' // 内部
              that.nodes[i].codeName = that.leftList[f].name
            }
          }
        }
      }
      that.EC = this.$echarts.init(this.$el)
      let jsondata = {}
      jsondata = {
        categories: that.categoryArray,
        nodes: that.nodes,
        links: that.links
      }
      setTimeout(() => {
        that.createGraph(that.EC, jsondata)
      }, 500)
    },
    getImgData(
      imgSrc,
      radius,
      center = {
        x: 0,
        y: 0
      }
    ) {
      return new Promise(resolve => {
        const canvas = document.createElement('canvas')
        const contex = canvas.getContext('2d')
        const img = new Image()
        img.crossOrigin = ''
        const diameter = 2 * radius
        img.onload = function() {
          canvas.width = diameter
          canvas.height = diameter
          contex.clearRect(0, 0, diameter, diameter)
          contex.save()
          contex.beginPath()
          contex.arc(radius, radius, radius, 0, 2 * Math.PI) // 画出圆
          contex.clip() // 裁剪上面的圆形
          contex.drawImage(img, center.x - radius, center.y - radius, diameter, diameter, 0, 0, diameter, diameter) // 在刚刚裁剪的园上画图
          contex.restore() // 还原状态
          resolve(canvas.toDataURL('image/png', 1))
        }
        img.src = imgSrc
      })
    },
    getImg() {
      for (let i = 0; i < this.imgArr.length; i++) {
        this.newImg.push(this.getImgData(this.imgArr[i], 30, { x: 150, y: 80 }))
      }
    },
    getNewImg() {
      Promise.all(this.newImg).then(images => {
        for (let x = 0; x < this.nodes.length; x++) {
          this.nodes[x].symbol = `image://${images[x]}`
          this.nodes[x].symbolSize = 30
        }
      })
    },
    getOption(graphInfo) {
      console.log('graphInfo', graphInfo)
      // node.itemStyle = null;//
      // node.symbolSize = node.size;// 强制指定节点的大小
      // Use random x, y
      let that = this
      graphInfo.nodes.forEach(function(node, i) {
        node.x = node.y = null
        node.draggable = true
      })
      let title = graphInfo['title']
      let nodes = graphInfo['nodes']
      let links = graphInfo['links']
      let categories = graphInfo['categories']
      let option = {
        title: {
          text: title,
          x: 'right',
          y: 'bottom'
        },
        toolbox: {
          show: false
        },
        tooltip: {
          formatter: data => {
            console.log('formatter', data)
            let str = ''
            let code = ''
            if (Object.keys(data.data).length > 0 && data.data.bgangRelationsTaskNumbersList) {
              for (let i = 0; i < data.data.bgangRelationsTaskNumbersList.length; i++) {
                if (data.name === data.data.bgangRelationsTaskNumbersList[i].phone) {
                  code = data.data.bgangRelationsTaskNumbersList[i].name
                }
              }
            }
            if (data.dataType === 'node') {
              str = `代号：${code} 电话：${data.name} 通联：${data.value}次`
            } else {
              str = `${data.data.source} 与 ${data.data.target} 通联`
            }
            return str
          }
        },
        series: [
          {
            type: 'graph',
            layout: 'force',
            name: title,
            ribbonType: false,
            draggable: false,
            focusNodeAdjacency: false,
            categories: categories,
            label: {
              normal: {
                show: true,
                fontSize: 10,
                formatter(params) {
                  // 以左侧表格中的排序作为图表内的数字显示
                  let order = null
                  for (let i = 0; i < that.leftList.length; i++) {
                    if (params.name === that.leftList[i].msisdn) {
                      order = i + 1
                    }
                  }
                  return order
                }
              }
            },
            useWorker: false,
            minRadius: 10,
            maxRadius: 50,
            gravity: 0,
            scaling: 0,
            roam: false,
            data: nodes,
            links: links,
            symbol: 'circle',
            symbolSize: 30,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  fontSize: 10,
                  // position: 'bottom',
                  textStyle: {
                    color: '#002e60',
                    padding: [2, 3],
                    borderRadius: 2
                  }
                },
                nodeStyle: {
                  brushType: 'both',
                  borderColor: 'rgba(255,215,0,0.4)',
                  borderWidth: 1
                },
                lineStyle: {
                  show: true,
                  color: 'target', // 决定边的颜色是与起点相同还是与终点相同
                  curveness: 0.3 // 边的曲度，支持从 0 到 1 的值，值越大曲度越大。
                }
              }
            },
            force: {
              edgeLength: [0, 150], // 线的长度，这个距离也会受 repulsion，支持设置成数组表达边长的范围
              repulsion: 600 // 节点之间的斥力因子。值越大则斥力越大
            },
            lineStyle: {
              normal: {
                opacity: 0.9,
                color: '#036d9a'
              }
            }
          }
        ]
      }
      return option
    },
    createGraph(myChart, mygraph) {
      // 设置option样式
      let option = this.getOption(mygraph)
      myChart.setOption(option)
    }
  }
}
</script>
<style lang="less">
.guanxitu_box {
  .none_box {
    position: absolute;
    top: 50%;
    left: 20%;
  }
}
</style>
